const fileDom = document.querySelector('input[type=file]');
const btn = document.querySelector('button');
const text = document.querySelector('textarea');
let html = "";
function loadImage(){
    const file = fileDom.files[0];
    if(!file){
        return null;
    }
    const objUrl = URL.createObjectURL(file);
    const img = new Image();
    //
    return new Promise((resolve,reject)=>{
        img.onload = () => {
            resolve(img);
        }
        img.onerror = () => {
            resolve(null);
        }
        img.src = objUrl;
    })
}
function createHTML(width,height,bmp){
    const shadowCSSFragments = []; // 阴影css片段
    const shadowCSSHover = [];     // 鼠标移入的颜色
    for(let r = 0; r < height; r++){
        for (let c = 0; c < width; c++) {
            const i = r * width + c;
            const 
                R = bmp[i * 4],
                G = bmp[i * 4 + 1],
                B = bmp[i * 4 + 2],
                A = bmp[i * 4 + 3] / 255;
            shadowCSSFragments.push(`${c + 1}px ${r}px rgba(${R},${G},${B},${A})`);
            // 使用filter可能更合适
            shadowCSSHover.push(`${c + 1}px ${r}px rgba(${255 - R},${255 -G},${255 -B},${A})`);
        }
    }
    return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
.shadow-img{
    width: ${width}px;
    height: ${height}px;
}
.shadow-img .inner{
    width: 1px;
    height: 1px;
    box-shadow: ${shadowCSSFragments.join(',')};
    transition: 1.5s;
}
.shadow-img:hover .inner{
    box-shadow: ${shadowCSSHover.join(',')};
}
</style>
</head>
<body>
<div class="shadow-img">
<div class="inner"></div>
</div>
<!--如果该部分js代码直接放在html文件中，解析到</body>会终止解析-->
</body>
</html>`;
// 如果界面渲染出该段及以后内容，你可能是把模板代码放入了html文件中，模板内的</body>会自动配对，终止解析
}
function download(){
    let blob = new Blob([html],{
        type: 'text/html'
    });
    let url = window.URL.createObjectURL(blob);
    let a = document.createElement('a');
    a.href = url;
    a.style.display = "none";
    a.download = "demo.html";
    a.click();
}
async function generate(){
    const img = await loadImage();
    if(!img){
        return;
    }
    const cvs = document.createElement("canvas");
    cvs.width = img.width;
    cvs.height = img.height;
    const ctx = cvs.getContext("2d");
    ctx.drawImage(img,0,0);

    const bmp = ctx.getImageData(0,0,img.width,img.height).data;
    html = createHTML(img.width,img.height,bmp);
    text.value = html;
}
btn.onclick = download;
fileDom.onchange = generate;